﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using FacebookApp.SharedLibraries;
using ThangNM_LIB.FUNC;
using DataAccessObject;
using EntityObject;

namespace FacebookApp
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AccountEO _AccountEO = new AccountEO();
                if (!String.IsNullOrEmpty(Request.QueryString["fb"]))
                {
                    FacebookClient FBClient = new FacebookClient();
                    FBClient.AppId = OtherEx.getAppSettings("Facebook_AppId");
                    FBClient.AppSecret = OtherEx.getAppSettings("Facebook_AppSecret");
                    FBClient.AccessToken = Request.QueryString["fb"];
                    String strJson = OtherEx.Facebook_Graph_API_Get(FBClient, String.Format(Constants.Facebook_Option._x_yz, Constants.Facebook_Param.me, Constants.Facebook_Param.user_param_ex, ""));
                    FacebookEO.User objFB_User = new FacebookEO.User();
                    objFB_User = (FacebookEO.User)JsonEx.Json2Object(strJson, objFB_User.GetType());
                    if (CommonsCheck.Object_OK(objFB_User))
                    {
                        _AccountEO = new AccountEO(1, Convert.ToInt64(objFB_User.id), objFB_User.link, objFB_User.name, FBClient.AccessToken);
                        if ((new AccountDAO()).Insert_Update_Delete(_AccountEO, ConstEx.Insert_Update_Delete.Update_21))
                            Response.Redirect(Request.Url.AbsoluteUri);
                    }
                }
                else
                {
                    _AccountEO.PK_iAID = 1;
                    _AccountEO = (new AccountDAO()).SelectItem(_AccountEO);
                    if (CommonsCheck.Object_OK(_AccountEO) && !String.IsNullOrEmpty(_AccountEO.sFToken))
                    {
                        txtToken.Text = _AccountEO.sFToken;
                        btnLogin.Visible = false;
                        btnLogout.Visible = true;
                    }
                    else
                    {
                        txtToken.Text = "";
                        btnLogin.Visible = true;
                        btnLogout.Visible = false;
                    }
                }
            }
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            AccountEO _AccountEO = new AccountEO(1, 0, "", "", "");
            if ((new AccountDAO()).Insert_Update_Delete(_AccountEO, ConstEx.Insert_Update_Delete.Update_21))
                txtToken.Text = "";
        }
    }
}